﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using AD.Pms.Core.ClientApi;
using AD.Pms.Core.EnumHelper;
using AD.Pms.Service.DtoModel;
using AD.Pms.Service.Interfaces;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;

namespace AD.Pms.Api.Controllers.V1
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class PushController : ControllerBase
    {
        private readonly IPushService _pushService;
        private readonly IHttpClientFactory _httpClientFactory;

        public PushController(IPushService pushService, IHttpClientFactory httpClientFactory)
        {
            _pushService = pushService;
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetCaptcha()
        {
            var res = new ApiResult<Dictionary<string, string>>();
            var result = await _pushService.GetCaptchaAsync();
            var image = result.Item1;
            var codeid = result.Item2;
            if (!string.IsNullOrEmpty(image) && !string.IsNullOrEmpty(codeid))
            {
                res.data = new Dictionary<string, string>()
                {
                    {"image", image}
                };
                HttpContext.Session.SetString("codeid", codeid);
                return new JsonResult(res);
            }
            else
            {
                res.statusCode = (int) ApiEnum.Error;
                res.message = "服务器出错";
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 发送验证码短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SendSmsCode([FromBody] string phone, [FromBody] string code)
        {
            var res = new ApiResult<Dictionary<string, string>>();
            if (string.IsNullOrEmpty(HttpContext.Session.GetString("codeid")))
            {
                res.statusCode = (int) ApiEnum.ParameterError;
                res.message = "验证码已过期";
                return new JsonResult(res);
            }

            if (string.IsNullOrEmpty(code))
            {
                res.statusCode = (int) ApiEnum.ParameterError;
                res.message = "验证码不能为空";
                return new JsonResult(res);
            }

            if (string.IsNullOrEmpty(phone))
            {
                res.statusCode = (int) ApiEnum.ParameterError;
                res.message = "手机号不能为空";
                return new JsonResult(res);
            }

            var result = await _pushService.PushSMSCodeAsync(phone, code, HttpContext.Session.GetString("code"),
                Request.HttpContext.Connection.RemoteIpAddress.ToString());
            HttpContext.Session.Remove("codeid");
            if (result)
            {
                return new JsonResult(res);
            }
            else
            {
                res.statusCode = (int) ApiEnum.Error;
                res.message = "服务器出错";
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 推送接口
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pushtype"></param>
        /// <param name="pushUserType"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SendUserSmsMessage([FromBody] string code, [FromBody] PushType pushtype,
            PushUserType pushUserType,
            [FromBody] string content)
        {
            var res = new ApiResult<Dictionary<string, string>>();
            if (string.IsNullOrEmpty(HttpContext.Session.GetString("codeid")))
            {
                res.statusCode = (int) ApiEnum.ParameterError;
                res.message = "验证码已过期";
                return new JsonResult(res);
            }

            if (string.IsNullOrEmpty(code))
            {
                res.statusCode = (int) ApiEnum.ParameterError;
                res.message = "验证码不能为空";
                return new JsonResult(res);
            }

            int pageindex = 1;
            int pagesize = 20;
            var useraccounts = await _pushService.GetUserAccountByPushUserTypeAsync(pushUserType, pageindex, pagesize);
            var result = true;
            if (useraccounts.Count > 0)
            {
                do
                {
                    result &= await _pushService.PushByUserAccountInfoAsync(useraccounts.AsEnumerable(), content,
                        HttpContext.Session.GetString("codeid"),
                        Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                        code, pushtype);
                    if (useraccounts.HasNextPage)
                    {
                        pageindex++;
                        useraccounts =
                            await _pushService.GetUserAccountByPushUserTypeAsync(pushUserType, pageindex, pagesize);
                    }
                } while (useraccounts.HasNextPage);
            }

            return new JsonResult(res);
        }
    }
}